#pragma once
#include <openssl/ssl.h>
#include <openssl/err.h>

#include <iostream>

class SslContext {
public:
    SslContext(const std::string& cert_path, const std::string& key_path) {
        ctx_ = SSL_CTX_new(TLS_server_method());
        SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_SERVER);

        SSL_CTX_sess_set_cache_size(ctx_, 1024 * 1024);

        SSL_CTX_set_timeout(ctx_, 7200);
        
        if (!ctx_) {
            throw std::runtime_error("SSL_CTX_new failed");
        }

        if (SSL_CTX_use_certificate_file(ctx_, cert_path.c_str(), SSL_FILETYPE_PEM) <= 0) {
            SSL_CTX_free(ctx_);
            throw std::runtime_error("Failed to load certificate");
        }

        if (SSL_CTX_use_PrivateKey_file(ctx_, key_path.c_str(), SSL_FILETYPE_PEM) <= 0) {
            SSL_CTX_free(ctx_);
            throw std::runtime_error("Failed to load private key");
        }

        if (!SSL_CTX_check_private_key(ctx_)) {
            SSL_CTX_free(ctx_);
            throw std::runtime_error("Private key does not match certificate");
        }

        std::cout << "SSL context initialized successfully"<<std::endl;
    }

    ~SslContext() {
        if (ctx_) {
            SSL_CTX_free(ctx_);
        }
    }

    SSL_CTX* get() const { return ctx_; }

private:
    SSL_CTX* ctx_;
};